<script setup lang="ts">
import { ref, watch } from 'vue'

const props = defineProps({
  showCode: {
    type: Boolean,
    default: true
  }
})
const startTime = ref<number>(10)
const isFlag = ref(true)

const timer = (): ReturnType<typeof setInterval> =>
  setInterval(() => {
    startTime.value--
    if (startTime.value == 0) {
      clearInterval(timer())
      isFlag.value = false
      startTime.value = 10
    }
  }, 1000)

watch(
  () => props.showCode,
  () => {
    if (props.showCode) {
      isFlag.value = true
      timer()
    } else {
      isFlag.value = false
      clearInterval(timer())
    }
  },
  {
    immediate: true
  }
)

const emit = defineEmits(['getCodeClick'])
const getCodeClick = () => {
  isFlag.value = true
  emit('getCodeClick')
}
// onMounted(() => {
//   timer(startTime.value)
// })
</script>

<template>
  <div class="count-down">
    <el-button :disabled="isFlag" @click="getCodeClick" v-if="isFlag">
      <span class="number">{{ startTime }} s</span>
    </el-button>
    <el-button @click="getCodeClick" v-if="!isFlag" class="code-text">
      <span class="reget">重新获取验证码</span>
    </el-button>
  </div>
</template>
<style scoped lang="less">
.count-down {
  .el-button {
    &.code-text {
      color: var(--primary-color);
    }
  }
}
</style>
